package it.univaq.mancoosi.injectors.systemconfiguration.managers.ubuntu;


import it.univaq.mancoosi.injectors.systemconfiguration.managers.UserManager;
import it.univaq.mancoosi.injectors.systemconfiguration.utils.ProcessCommand;
import it.univaq.mancoosi.mancoosimm.Alternative;
import it.univaq.mancoosi.mancoosimm.User;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;

import org.eclipse.emf.ecore.util.EcoreUtil;

public class UbuntuUserManager extends UserManager {

	protected UbuntuUserManager(){
		this.configuration = UbuntuConfigurationManager.getInstance().getConfiguration();
		this.groupManager = UbuntuGroupManager.getInstance();
	}

	public static UserManager getInstance(){
		if (INSTANCE == null)
			INSTANCE = new UbuntuUserManager();
		return INSTANCE;
	}


	@Override
	public void synchronize() throws IOException {
		
		userMapReload();
		UbuntuGroupManager.getInstance().groupMapReload();

		UserManager.getInstance().createUsersFromSystem();
		
		Iterator<User> iterator = this.userMap.values().iterator();
		while (iterator.hasNext()) {
			User curr = iterator.next();
			if (!existsInTheSystem(curr.getName())) {
				this.userMap.remove(curr);
				EcoreUtil.delete(curr);
				//UbuntuFileSystemManager.getInstance().deleteFile(curr.getCurrent());
			}
		}
	}
	
	public boolean existsInTheSystem (String userName) {
		try {
			String[] cmd = {"/bin/sh","-c","usermod " + userName};
			BufferedReader input = ProcessCommand.getInstance().getErrorSream(cmd);	

			String line = input.readLine();

			if (line.contains("does not exist")) return false;
			else return true;
		}
		catch (Exception e) {
			e.printStackTrace();
			return true;
		}
	}

}
